<template>
  <div class="student" style="margin-top: 20px;">
    <div style="display: flex; align-items: center; margin-bottom: 20px;">
      <!-- 筛选条件 -->
      <el-row :gutter="20">
        <!-- 性别筛选框 -->
        <el-col :span="14">
          <span style="margin-right: 10px;">性别：</span>
          <el-select v-model="filterGender" placeholder="请选择性别">
            <el-option label="全部" value=""></el-option>
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-col>
        <!-- 关键词筛选框 -->
        <el-col :span="10">
          <el-input v-model="filterKeyword" placeholder="请输入姓名"></el-input>
        </el-col>
      </el-row>
      <el-button style="margin-left: 50px;" type="primary" @click="getStudents">查询</el-button>

    </div>

    <!-- 学生列表 -->
    <el-table :data="students" style="width: 1200px;"
              border
              :header-cell-style="{
                  background: '#DAF8D4',
                  color: '#333333',
                  fontWeight: 'bold',
                  fontSize: '20px',
              }">
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="年龄" prop="age"></el-table-column>
      <el-table-column label="年级" prop="grade"></el-table-column>
      <!-- 新增的字段：性别 -->
      <el-table-column label="性别" prop="gender"></el-table-column>
      <!-- 新增的字段：邮箱 -->
      <el-table-column label="邮箱" prop="email" width="200px"></el-table-column>
      <!-- 新增的字段：电话 -->
      <el-table-column label="电话" prop="phone" width="200px"></el-table-column>
      <!-- 新增的字段：地址 -->
      <el-table-column label="地址" prop="address"></el-table-column>
      <!-- 新增的字段：入学日期 -->
      <el-table-column label="入学日期" prop="enrollment_date" width="120px"></el-table-column>
      <el-table-column label="操作" width="180px">
        <template v-slot="scope">
          <div class="button-group">
            <!-- 编辑按钮 -->
            <el-button type="primary" size="medium" @click="editStudent(scope.row)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" size="medium" @click="deleteStudent(scope.row.id)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/导入按钮 -->
    <div style="display: flex; align-items: center;">
      <el-button type="success" style="margin-top: 20px;" @click="addStudent()">新增</el-button>
      <el-button type="primary" style="margin-top: 20px; margin-left: 20px;" @click="importExcel()">导入</el-button>
      <el-button type="primary" style="margin-top: 20px; margin-left: 20px;" @click="exportExcel()">导出</el-button>
    </div>

    <!--导入对话框-->
    <el-dialog
        :visible.sync="importDialogVisible"
        title="文件上传"
        :width="'400px'"
        @close="closeDialog"
    >
      <div class="file-upload-container">
        <el-upload
            class="file-upload"
            action=""
            :on-change="handleFile"
            :file-list="fileList"
            :auto-upload="false"
            list-type="text"
            drag
        >
          <div class="upload-text">
            <i class="el-icon-upload"></i>
            <div>点击或拖拽文件到这里上传</div>
          </div>
        </el-upload>
        <!-- 设置上方间隔 -->
        <div style="height: 10px;"></div>
        <div style="display: flex; justify-content: center;">
          <!-- 将按钮居中 -->
          <el-button type="primary" @click="uploadFiles" style="margin-top: 20px;">导入</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑/添加学生信息的对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="编辑学生信息">
      <el-form :model="currentStudent" ref="studentForm" :rules="rules" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="currentStudent.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="currentStudent.age"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="currentStudent.grade"></el-input>
        </el-form-item>
        <!-- 性别下拉框 -->
        <el-form-item label="性别" prop="gender">
          <el-select v-model="currentStudent.gender" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <!-- 新增的字段：邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentStudent.email"></el-input>
        </el-form-item>
        <!-- 新增的字段：电话 -->
        <el-form-item label="电话" prop="phone">
          <el-input v-model="currentStudent.phone"></el-input>
        </el-form-item>
        <!-- 新增的字段：地址 -->
        <el-form-item label="地址" prop="address">
          <el-input v-model="currentStudent.address"></el-input>
        </el-form-item>
        <!-- 新增的字段：入学日期 -->
        <el-form-item label="入学日期" prop="enrollment_date">
          <el-date-picker
              v-model="currentStudent.enrollment_date"
              value-format="yyyy-MM-dd"
              type="date"></el-date-picker>
        </el-form-item>
      </el-form>

      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveStudent">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script>

export default {
  name: 'StudentView',
  data() {
    return {
      // 学生列表数据
      students: [], // 初始为空数组
      fileList: [],
      filterGender : '',
      filterKeyword : '',
      // 当前编辑/添加的学生信息
      currentStudent: {
        id: 0,
        name: '',
        age: '',
        grade: '',
        gender: '',
        email: '',
        phone: '',
        address: '',
        enrollment_date: ''
      },
      // 是否显示编辑/添加对话框
      dialogVisible: false,
      // 导入对话框
      importDialogVisible: false,
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const reg = /^\d+$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error('年龄必须为数字值'));
              }
            },
            trigger: 'blur'
          }
        ],
        grade: [
          { required: true, message: '请输入年级', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getStudents(); // 在组件创建时获取学生数据
  },
  methods: {
    // 异步获取学生数据
    async getStudents(){
      try {
        let params = {
          pageNumber: 1,
          pageSize: 10,
          filterGender: this.filterGender,
          filterKeyword: this.filterKeyword
        };
        const response = await this.$http.post('student/getStudents',params);
        console.log(response)
        this.students = response.data.data; // 假设返回的数据格式为数组
      } catch (error) {
        console.error('Error fetching students:', error);
      }
    },
    // 添加学生
    addStudent() {
      this.currentStudent = {
        id: 0,
        name: '',
        age: '',
        grade: '',
        gender: '',
        email: '',
        phone: '',
        address: '',
        enrollment_date: ''
      };
      this.dialogVisible = true;
    },
    // 编辑学生
    editStudent(student) {
      this.currentStudent = Object.assign({}, student);
      this.dialogVisible = true;
    },
    // 保存学生信息
    saveStudent() {
      // 表单验证
      this.$refs.studentForm.validate(valid => {
        if (valid) {
          // 新增或更新学生信息
          this.$http.post('student/saveStudent', this.currentStudent)
              .then(() => {
                // 处理成功响应
                this.getStudents(); // 重新请求查询接口
                this.dialogVisible = false;
              })
              .catch(error => {
                // 处理错误响应
                console.error('Error saving student:', error);
              });
        }
      });
    },
    // 删除学生
    deleteStudent(id) {
      this.$confirm('确认删除该学生吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用后端接口删除学生
        this.$http.get(`student/deleteStudent?id=${id}`)
            .then(() => {
              // 处理成功响应
              this.getStudents(); // 重新请求查询接口
              this.$message.success('删除成功');
            })
            .catch(error => {
              console.error('删除学生失败', error);
              this.$message.error('删除学生失败');
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 导入相关
    handleFile(file) {
      // 将文件添加到文件列表中
      this.fileList.push(file);
      console.log(this.fileList)
      // 返回 false 可以阻止上传
      return false;
    },
    importExcel() {
      this.importDialogVisible = true;
    },
    // 关闭弹窗
    closeDialog() {
      this.importDialogVisible = false;
    },
    uploadFiles() {
      // 创建一个 FormData 对象，用于存储文件数据
      let formData = new FormData();
      // 将每个文件添加到 FormData 对象中
      this.fileList.forEach((file) => {
        formData.append('file', file.raw || file);
      });

      // 发送 POST 请求到后端接口
      let url = 'student/import';
      this.$http.post(url, formData)
          .then(response => {
            // 处理上传成功的响应
            console.log(response.data);
            if (response.data.code === '200') {
              // 如果 code 为 200，表示成功
              this.$message.success('学生信息导入成功，共计导入' + response.data.message + '条数据。');
            } else {
              // 如果 code 不是 200，表示上传失败
              this.$message.error(`上传失败：${response.data.message}`);
            }
            this.getStudents(); // 重新请求查询接口
            this.importDialogVisible = false;
          })
          .catch(error => {
            // 处理上传失败的错误
            this.$message.error(`上传失败：${error}`);
          });
    },
    exportExcel() {
      let url = 'student/export';
      this.$http.get(url, { responseType: 'blob' })
          .then(response => {
            // 处理下载成功的响应
            const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = '学生信息.xlsx';
            link.click();
          })
          .catch(error => {
            // 处理下载失败的错误
            if (error.response && error.response.status === 201) {
              // 如果后端返回了错误信息
              this.$message.error(`下载失败：${error.response.data.message}`);
            } else {
              // 如果是其他类型的错误，直接显示错误信息
              this.$message.error(`下载失败：${error}`);
            }
          });
    }
  }
};
</script>

<style>

.button-group {
  display: flex;
  justify-content: space-between;
}


.student {
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>
